import bluebird from 'bluebird';
import db from '../db';
import log from '../../../log';

function saveAnswers(que, answers) {
    log.debug('开始保存问卷答案');

    return db.exec(model => model('xp_answers').query(qb => {
        qb.where('queId', que.id);
        qb.andWhere('userId', que.createUserId);
    })
        .destroy()
        .then(() => model('xp_questionnaires').query(qb => {
            qb.where({id: que.id});
        }).list().then(res => {
            res = res.toJSON() || [];
            if (res.length === 0) {
                return model('xp_questionnaires').forge().save(que, {method: 'insert'});
            }
            return model('xp_questionnaires').forge({id: que.id}).save(que, {method: 'update'});
        }))
        .then(() =>
             bluebird.all(answers.map(a => model('xp_answers').forge().save(a, {method: 'insert'})))
        ))
        .then(() => que.id);
}

function getAnswers(queId) {
/*

    return db.get('xp_questions').query(qb => {
        qb.where('xp_questions.queId', queId);
        qb.innerJoin('xp_answers', ['xp_answers.questionId', '=', 'xp_questions.id']);

        //统计参与人数
        const t1 = db._.raw('select xp_answers.optionId from xp_questionnaires where xp_questionnaires.queTempId=xp_questionnairetemplates.id ').wrap('(', ') totalUser');
        qb.select('*', t1);
    }).fetchAll({
        columns: cols
    });


*/
    const cols = ['xp_answers.questionId', 'xp_answers.value', 'xp_answers.optionId'];

    return db.get('xp_answers').query(qb => {
        qb.innerJoin('xp_questions', 'xp_answers.questionId', 'xp_questions.id');
        qb.where('xp_answers.queId', queId);
    }).fetchAll({
        columns: cols
    });
}
export {saveAnswers, getAnswers};
